function checkValue(obj) {
	var value = $(obj).val(); //.attr('value');
	if(value != '' && !checkEnName(value)) {
		$(obj).addClass('warning');
	}
}

function rmError(obj) {
	$(obj).removeClass('warning');
}

//获取二维数组值及转json数据格式
function getApiRequestParam(dom_name, params, params_num) {
	var api_request_param = $("input[name^='" + dom_name + "']");
	//console.log(api_request_param);
	var json_params = new Array();
	var array_num = Math.floor(api_request_param.length / params_num);
	for(var j = 0; j < array_num; j++) {
		//json_params[j] = new Array();
		json_params[j] = new Object();
	}
	for(var i = 0; i < api_request_param.length; i++) {
		var num = i % params_num;
		var key = Math.floor(i / params_num);
		json_params[key][params[num]] = api_request_param[i].value;
	}
	//console.log(json_params);
	//console.log(JSON.stringify(json_params));return false;
	return JSON.stringify(json_params);
}

$(function() {
	//请求协议
	$("._service_host_protol").change(function() {
		var selectedvalue = $("input[name='service_proto']:checked").val();
		$("#protol_id").text(selectedvalue);
	});
	//request headers 追加
	$('._add_request_headers').click(function() {
		var user1 = Object();
		jPut.jput_format_request.append(user1);
	});
	$("#dlanxhover").click(function() {
		$(this).parent().toggleClass("");
		$(this).parent().prevAll("#dlanxhout").removeClass("bg")
		$(this).parent().nextAll("#dlanxhout").removeClass("bg")
		$(this).parent().next().slideToggle();
		$(this).parent().prevAll("#dlanxhover").slideUp("slow");
		$(this).parent().next().nextAll("#dlanxhover").slideUp("slow");
		//return false;
	});
	//response headers 追加
	$('._add_response_headers').click(function() {
		//defining new user
		var user2 = Object();
		//appening to jput variable
		jPut.jput_format_response.append(user2);
	});
	jPut.jput_format_request.data = [{
		"name": "",
		"value": ""
	}];
	jPut.jput_format_response.data = [{
		"name": "",
		"email": ""
	}];
	$("._blur_num_rz").blur(function() {
		var timeout = $("._blur_num_rz").val();
		if(stringIsNull(timeout)) {
			add_auth_error('service_timeout', '请输入服务超时时间');
			return;
		}
		//不为空的时候，需要判断是否为数字
		if(!checkNum(timeout)) {
			add_auth_error('service_timeout', '请输入正确的服务超时时间');
		}
	});
	$("._blur_num_rz").focus(function() {
		rm_auth_error('service_timeout');
	});
	$("._service_logo").click(function() {
		rm_auth_error('file_upload');
	});
	$('#selected_category').click(function() {
		rm_auth_error('selected_category');
	});
	$(document)
	.on('click', '._request_head_del', function() {//高级设置--删除request_head		
		var that = $(this);
		that.parent().parent('._raw_request_head').remove();
	})
	.on('click', '._response_head_del', function() {//高级设置--删除response_head		
		var that = $(this);
		that.parent().parent('._raw_response_head').remove();
	})
	.on('click', '._add_confirm', function() {//发布/保存服务				
		var that = $(this); //用于判断是继续添加API还是仅是保存服务
		var t = that.attr('data-id');
		var service_name = $("._service_name").val();
		var service_name_en = $("._service_name_en").val();
		var service_introduction = $("._service_introduction").val();
		var service_logo = $("._service_logo").val();
		var service_timeout = $("._service_timeout").val();
		var service_host = $('._service_host').val();
		var service_request_heads = JSON.parse(getApiRequestParam('request', ['name', 'value'], 2));
		var service_response_heads = JSON.parse(getApiRequestParam('response', ['name', 'value'], 2));
		//请求协议头
		var service_protol = $("input[name='service_proto']:checked").val();
		var category_id = $('#selected_category').children('input[name="selected_category"]').val().split('-')[1];
		if(category_id == 0 || category_id == '') {
			add_auth_error('selected_category', '请选择服务分类');
		}
		//二级分类id.
		var secCateId = $('#select-crumbs2').children('input[name="select-crumbs2"]').val()
		//参数为空判断
		batchVer('_blur_rz');
		//判断是否有未填的必填项
		if($('.warning').length > 0) {
			//offsetTop兼容性解决
			function offsetTop(elements) {
				var top = elements.offsetTop;
				var parent = elements.offsetParent;
				while(parent !== null) {
					top += parent.offsetTop;
					parent = parent.offsetParent;
				}
				return top;
			};
			//本页跳转
			$('#tab1').scrollTop(offsetTop($('.warning')[0]) - 160)
			return;
		}
		if(service_logo == '') {
			add_auth_error('file_upload', '请为您的服务上传LOGO。');
			return;
		}
		//有错误样式不允许提交
		if(haserror('_blur_rz')) {
			return;
		}
		var c = service_host.charAt(service_host.length - 1);
		if(c == '/') {
			add_auth_error('service_host', '请输入正确的域名');
			return;
		}
		if(t == 'add_api') {
			function run_waitMe(register_api) {
				$('#register_api').waitMe({
					effect: 'ios',
					bg: 'rgba(16,128,242,0)',
					text: '保存中...',
					color: '#fff',
					padding: '10px',
					sizeW: '',
					sizeH: '',
					source: 'img.svg'
				});
			}
			var cur = $(this);
			// 按钮置为不可点击
			it_enable(cur, true);
			$('#register_api').text('');
			$('#register_api').attr("disabled", "true");
			run_waitMe('register_api');
		} else if(t == 'list') {
			function run_waitMe(register) {
				$('#register').waitMe({
					effect: 'ios',
					bg: 'rgba(16,128,242,0)',
					text: '发布中...',
					color: '#fff',
					padding: '10px',
					sizeW: '',
					sizeH: '',
					source: 'img.svg'
				});
			}
			var cur = $(this);
			// 按钮置为不可点击
			it_enable(cur, true);
			$('#register').attr("disabled", true);
			$('#register').text('');
			run_waitMe('register');

		}
		//设置发送数据
		var data = {};
		data.service_name = service_name;
		data.service_name_en = service_name_en;
		data.service_introduction = service_introduction;
		data.service_logo = service_logo;
		data.service_timeout = service_timeout;
		data.service_host = service_host;
		data.service_request_heads = service_request_heads;
		data.service_response_heads = service_response_heads;
		data.service_proto = service_protol;
		data.category_id = category_id;
		data.tid = secCateId //二级分类id
			//ajax请求
		$.ajax({
			url: '/apiworks/add.html',
			type: 'POST',
			dataType: 'json',
			async: true,
			data: data,
			success: function(req) {
				if(req.status == 200) {
					if(t == 'add_api') {
						location.href = "/apiworks/apiAdd.html?service_id=" + req.data;
						$('#register_api').attr("disabled", false);
						$('#register').waitMe('hide');
						$('#register').text('发布服务');
						return false;
					} else if(t == 'list') {
						location.href = "/apiworks/servicelist";
						it_enable(cur, false);
						$('#register').attr("disabled", false);
						$('#register_api').waitMe('hide');
						$('#register_api').text('保存,并添加API');
						return false;
					}
				} else {
					$('#register').attr("disabled", false);
					$('#register_api').attr("disabled", false);
					$('#register').waitMe('hide');
					$('#register').text('发布服务');
					$('#register_api').text('保存,并添加API');
					if(req.status == 1) {
						add_auth_error(req.data, req.msg)
					} else {
						show_msg({
							msg: req.msg,
							type: 'error',
							time: 2000
						});
					}
					return false;
				}
			},
			error: function() {
				it_enable(cur, false);
				$('#register').waitMe('hide');
				$('#register_api').waitMe('hide');
				$('#register').text('发布服务');
				$('#register_api').text('保存,并添加API');
				show_msg({
					msg: '系统异常',
					type: 'error',
					time: 2000
				});
			}
		});
	});

	//下拉列表数据
	var seLevelObj = JSON.parse($('._categoryObj').val())

	function newObj(obj) {
		var newObj = {}
		for(var key in obj) {
			var newkey = key.split('-')[1]
			newObj[newkey] = obj[key]
		}
		return newObj
	}
	var newseLevelObj = newObj(seLevelObj)
		//第一个下拉栏
	for(var firstList in seLevelObj) {
		$('._selecte_category_list:eq(0)').append('<option value=' + firstList + '>' + seLevelObj[firstList].name + '</option>')
	}
	$('._selecte_category_list:eq(0)').selectlist({
		zIndex: 10,
		width: 200,
		height: 40,
		onChange: function() {
			$('#select-crumbs2').remove()
			var childObj = seLevelObj[$('#selected_category .selected').attr('data-value')].children
			var htmlArr = ['<select id="select-crumbs2" class="class _selecte_category_list fl">']
			if(childObj) {
				for(var child in childObj) {
					htmlArr.push('<option value=' + child + '>' + childObj[child].name + '</option>')
				}
			} else {
				htmlArr.push('<option value="0">暂无分类</option>')
			}
			htmlArr.push('</select>')
			$('._secList').html(htmlArr.join(''))
			$('._selecte_category_list:eq(1)').selectlist({
				zIndex: 10,
				width: 200,
				height: 40
			});
		}
	});
	//第二个下拉栏
	var fatherId = $('._selecte_category_list:eq(0) ul li:eq(0)').attr('data-value')
	if(seLevelObj[fatherId].children) {
		for(var secondList in seLevelObj[fatherId].children) {
			if($('._selecte_category_list:eq(1) option')) {
				$('._selecte_category_list:eq(1)').append('<option value=' + secondList + '>' + seLevelObj[fatherId].children[secondList].name + '</option>')
			} else {
				$('._selecte_category_list:eq(1)').append('<option selected="selected" value=' + secondList + '>' + seLevelObj[fatherId].children[secondList].name + '</option>')
			}
		}
	} else {
		$('._selecte_category_list:eq(1)').append('<option selected="selected" value=0>暂无分类</option>')
	}
	$('._selecte_category_list:eq(1)').selectlist({
		zIndex: 10,
		width: 200,
		height: 40
	});
});